<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>随机验证码</title>
<style type="text/css">
#code{color:blue; letter-spacing:2px; font-size:14px; font-weight:bold;}
</style>
</head>

<body>
<input type="text" id="input">
<input type="button" id="code">
<input type="button" value="提交" id="check">

<script type="text/javascript">

	var input = document.getElementById('input');
	var code = document.getElementById('code');
	var check = document.getElementById('check');
	
	var fnCode = function(minLen,maxLen){
		var len = parseInt(Math.random()*(maxLen-minLen+1)+minLen);	//JS获取maxLen至minLen随机整数
		
		var codeVal = '';
		var codes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
		for(var i=0; i<len; i++){
			codeVal += codes[parseInt(Math.random()*codes.length)]
		}
		
		var reg = new RegExp(/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/);	//验证必须包含数字和字母
		if(reg.test(codeVal)){
			code.value = codeVal
		}else{
			fnCode(minLen,maxLen)
		}
	};
	
	var minLen = 4;
	var maxLen = 6;
	fnCode(minLen,maxLen);
	
	code.onclick = function(){
		fnCode(minLen,maxLen)
	};
	
	check.onclick = function(){
		if( input.value.toLowerCase() == code.value.toLowerCase() ){	//toLowerCase()转换为小写 不区分大小写
			alert('true')
		}else{
			alert('false');
			fnCode(minLen,maxLen);
			input.value = '';
		}
	}
</script>
</body>
</html>
